package com.mooral.web.action.user;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.validator.DynaValidatorForm;

import com.mooral.bean.Beans;
import com.mooral.bean.Categories;
import com.mooral.bean.Category;
import com.mooral.bean.Merchant;
import com.mooral.bean.User;
import com.mooral.context.Context;
import com.mooral.web.action.MooralAction;
import com.mooral.web.util.SorterUtils;

public class EditAction extends MooralAction {

	@Override
	public ActionForward perform(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			Context context) throws Exception {
		
		DynaActionForm dform = (DynaActionForm) form;
		
		User user = context.getUser();
		user.put("passwordConfirm", user.get("password"));
		
		// Usuario
		dform.set("user", user);
		
		// Categorias
		Categories categories = new Categories();
		categories.populate("SELECT id, parent_id as parentId, name FROM categories");
		dform.set("categories",  (new SorterUtils()).sortCategoriesByDependency(categories));
		
		// Categorias seleccionadas
		Categories categoriesSelected = new Categories();
		categoriesSelected.populate("SELECT categories.id, categories.parent_id as parentId, name FROM categories, categories_users WHERE categories.id =  categories_users.category_id and user_id = " + user.get("id"));
		String categoriesSelectedIds[] = new String[categoriesSelected.size()];
		
		for(int i=0 ; i < categoriesSelected.size() ; i++)
			categoriesSelectedIds[i] = ((Category)categoriesSelected.get(i)).get("id").toString();

		dform.set("categoriesSelected",  categoriesSelectedIds);
		
		return mapping.findForward(ACTION_SUCCESS);
	}

}
